#!/usr/bin/env python3

from menu import Menu
from random import randint
from student import Student
import pickle

class StudentManage(Menu):
    def __init__(self, **kargs):
        self.data = {}
        if "title" not in kargs:
            kargs['title'] = "学生成绩管理系统"
        super().__init__(**kargs)
        self.add("添加", self.addStu)
        self.add("修改", self.edit)
        self.add("查询", self.find)
        self.add("删除", self.delete)
        self.add("遍历", self.travel)
        self.add("存储", self.save)
        self.add("加载", self.load)

    def addStu(self, index):
        name = False
        while not name:
            name = input("\t请输入学生姓名: ")

        stu = Student(name)
        stu.age = randint(10, 30)
        stu.sex = ["男", "女"][randint(0, 1)]
        stu.en = randint(50, 100)
        stu.cn = randint(0, 100)

        self.data[stu.id] = stu

    def edit(self, index):
        pass

    def delete(self, index):
        pass

    def travel(self, index):
        for k, v in self.data.items():
            print("\t---->" + v)

        print()

    def find(self, index):
        pass

    @staticmethod
    def __getfile(mes, mode="rb"):
        filepath = input("\t%s(./db): " % mes)
        if not filepath:
            filepath = "./db"
        return open(filepath, mode)

    def load(self, index):
        data = pickle.load(self.__getfile("加载文件"))
        if (type(data) != dict
                or {'type', 'data', 'lastID'} - set(data)
                or data['type'] != 'kyo'):
            print("\t加载失败!!!")
        else:
            self.data = data['data']
            Student.setLastID(data['lastID'])
            print("\t加载成功!!")

    def save(self, index):
        savedata = {}
        savedata['type'] = "kyo"
        savedata['data'] = self.data
        savedata['lastID'] = Student.getLastID()
        pickle.dump(savedata, self.__getfile("存储到", "wb"))
        print("\t存储成功!!")

if __name__ == "__main__":
    StudentManage().run()
